# Maintainer: Alexey Pavlov <alexpux@gmail.com>
# Contributor: Jürgen Pfeifer <juergen@familiepfeifer.de>

_realname=OpenBLAS

pkgname="${MINGW_PACKAGE_PREFIX}-${_realname}-git"
pkgrel=1
pkgver=r830.66198fa
pkgdesc="OpenBLAS is an optimized BLAS library (mingw-w64)"
provides=("${MINGW_PACKAGE_PREFIX}-${_realname}")
arch=('any')
url="http://www.openblas.net/"
license=('custom')
groups=("${MINGW_PACKAGE_PREFIX}")
options=('strip' 'staticlibs')
depends=("${MINGW_PACKAGE_PREFIX}-gcc-libs")
makedepends=("git" 
    "${MINGW_PACKAGE_PREFIX}-gcc"
    "${MINGW_PACKAGE_PREFIX}-gcc-fortran")
source=("$_realname"::"git://github.com/xianyi/OpenBLAS")
sha1sums=('SKIP')

pkgver() {
  cd "$srcdir/$_realname"
  printf "r%s.%s" "$(git rev-list --count HEAD)" "$(git rev-parse --short HEAD)"
}

build() {
  mkdir -p ${srcdir}/build-${CARCH} && cd ${srcdir}/build-${CARCH}
  git clone ${srcdir}/${_realname} .
  make -f Makefile CC=gcc FC=gfortran LIBNAME=libopenblasp.a DYNAMIC_ARCH=1 2>make.err
}

package() {
  cd ${srcdir}/build-${CARCH}
  if [ -f libopenblas.dll ]; then
    if [ -f exports/libopenblas.def ]; then
      dlltool -D libopenblas.dll -d exports/libopenblas.def -l libopenblas.dll.a
    else
      echo "Cannot build export library" >&2
      exit 1
    fi
  else
    echo "DLL not found" >&2
    exit 1
  fi
  mkdir -p "${pkgdir}${MINGW_PREFIX}/bin"
  mkdir -p "${pkgdir}${MINGW_PREFIX}/lib"

  make $MAKEFLAGS -f Makefile LIBNAME=libopenblasp.a DESTDIR="${pkgdir}" PREFIX="${MINGW_PREFIX}" install

  if [ -f libopenblas.dll ]; then
    cp -f libopenblas.dll "${pkgdir}$MINGW_PREFIX/bin/"
  else
    echo "DLL not found" >&2
    exit 1
  fi

  if [ -f libopenblas.dll.a ]; then
    cp -f libopenblas.dll.a "${pkgdir}$MINGW_PREFIX/lib/"
  else
    echo "Export library not found" >&2
    exit 1
  fi

  if [ -f libopenblasp.a ]; then
    rm -f "${pkgdir}$MINGW_PREFIX/lib/libopenblasp.a"
    rm -f "${pkgdir}$MINGW_PREFIX/lib/libopenblas.a"
    cp -f libopenblasp.a "${pkgdir}$MINGW_PREFIX/lib/libopenblas.a"
  else
    echo "Static library not found" >&2
    exit 1
  fi

  # Copy Licencse
  mkdir -p ${pkgdir}${MINGW_PREFIX}/share/licenses/$_realname  
  cp -f ${srcdir}/${_realname}/LICENSE \
    ${pkgdir}${MINGW_PREFIX}/share/licenses/$_realname
  cp -f ${srcdir}/${_realname}/lapack-netlib/LICENSE \
    ${pkgdir}${MINGW_PREFIX}/share/licenses/$_realname/LICENSE-lapack
}
